<script setup>
import { ref } from 'vue'
import { useProductStore, useCartStore } from '../stores/02.定义store(组合式)'

// 获取store实例
const productStore = useProductStore()
const cartStore = useCartStore()

// 新商品表单数据
const newProduct = ref({
  name: '',
  price: 0,
  inventory: 1
})

// 添加新商品
function addNewProduct() {
  if (newProduct.value.name && newProduct.value.price > 0) {
    productStore.addProduct({
      name: newProduct.value.name,
      price: Number(newProduct.value.price),
      inventory: Number(newProduct.value.inventory)
    })
    // 重置表单
    newProduct.value = {
      name: '',
      price: 0,
      inventory: 1
    }
  }
}

// 折扣百分比
const discountPercent = ref(10)

// 应用折扣
function applyDiscount() {
  if (discountPercent.value > 0 && discountPercent.value <= 90) {
    productStore.applyDiscount(discountPercent.value)
  }
}
</script>

<template>
  <div class="tutorial-container">
    <header>
      <h1>02.定义store(组合式)</h1>
      <p class="subtitle">学习如何在组合式API中定义和使用store</p>
      
      <nav class="tutorial-nav">
        <router-link to="/01" class="nav-link">01.认识pinia</router-link>
        <router-link to="/02" class="nav-link">02.定义store(选项式)</router-link>
        <router-link to="/02c" class="nav-link">02.定义store(组合式)</router-link>
        <router-link to="/03" class="nav-link">03.state(选项式)</router-link>
        <router-link to="/03c" class="nav-link">03.state(组合式)</router-link>
        <router-link to="/04" class="nav-link">04.getters(选项式)</router-link>
        <router-link to="/04c" class="nav-link">04.getters(组合式)</router-link>
        <router-link to="/05" class="nav-link">05.actions(选项式)</router-link>
        <router-link to="/05c" class="nav-link">05.actions(组合式)</router-link>
      </nav>
    </header>

    <main>
      <section class="intro">
        <h2>定义Store</h2>
        <p>在Pinia中，store是使用<code>defineStore()</code>函数定义的。每个store都有一个唯一的ID，用于在开发工具中标识它。</p>
        
        <div class="code-example">
          <pre><code>// 基本的store定义
import { defineStore } from 'pinia'

export const useStore = defineStore('storeId', {
  // 状态
  state: () => ({
    count: 0,
    name: 'Eduardo'
  }),
  // 计算属性
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  // 方法
  actions: {
    increment() {
      this.count++
    }
  }
})</code></pre>
        </div>
      </section>

      <div class="demo-section">
        <div class="products-section">
          <h2>产品管理示例</h2>
          
          <!-- 添加新产品表单 -->
          <div class="card">
            <h3>添加新产品</h3>
            <div class="form-group">
              <label>产品名称</label>
              <input v-model="newProduct.name" type="text" placeholder="输入产品名称" />
            </div>
            <div class="form-group">
              <label>价格</label>
              <input v-model="newProduct.price" type="number" min="0" placeholder="输入价格" />
            </div>
            <div class="form-group">
              <label>库存数量</label>
              <input v-model="newProduct.inventory" type="number" min="1" placeholder="输入库存数量" />
            </div>
            <button @click="addNewProduct" class="btn primary">添加产品</button>
          </div>
          
          <!-- 产品列表 -->
          <div class="card">
            <h3>产品列表</h3>
            <div class="products-list">
              <div v-for="product in productStore.products" :key="product.id" class="product-item">
                <div class="product-info">
                  <h4>{{ product.name }}</h4>
                  <p>价格: ¥{{ product.price }}</p>
                  <p>库存: {{ product.inventory }}</p>
                </div>
                <div class="product-actions">
                  <button 
                    @click="cartStore.addToCart(product)" 
                    class="btn primary small"
                    :disabled="product.inventory <= 0"
                  >
                    加入购物车
                  </button>
                </div>
              </div>
            </div>
            
            <!-- 折扣应用 -->
            <div class="discount-section">
              <h4>应用折扣</h4>
              <div class="discount-form">
                <input v-model="discountPercent" type="number" min="1" max="90" placeholder="折扣百分比" />
                <span>%</span>
                <button @click="applyDiscount" class="btn secondary">应用折扣</button>
              </div>
            </div>
          </div>
          
          <!-- 购物车 -->
          <div class="card">
            <h3>购物车 ({{ cartStore.count }})</h3>
            <div v-if="cartStore.items.length === 0" class="empty-cart">
              <p>购物车为空</p>
            </div>
            <div v-else>
              <div class="cart-items">
                <div v-for="item in cartStore.items" :key="item.id" class="cart-item">
                  <div class="item-info">
                    <h4>{{ item.name }}</h4>
                    <p>数量: {{ item.quantity }}</p>
                    <p>单价: ¥{{ item.price }}</p>
                    <p>小计: ¥{{ item.price * item.quantity }}</p>
                  </div>
                  <div class="item-actions">
                    <button @click="cartStore.removeFromCart(item.id)" class="btn danger small">移除</button>
                  </div>
                </div>
              </div>
              <div class="cart-summary">
                <p class="total">总计: ¥{{ cartStore.total }}</p>
                <button @click="cartStore.clearCart()" class="btn secondary">清空购物车</button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <section class="explanation">
        <h2>组合式API中定义Store</h2>
        
        <div class="subsection">
          <h3>1. 基本结构</h3>
          <p>在组合式API中，我们使用<code>defineStore</code>函数定义store，它接收两个参数：</p>
          <ul>
            <li>一个唯一的ID，用于在开发工具中标识store</li>
            <li>一个包含state、getters和actions的选项对象</li>
          </ul>
        </div>
        
        <div class="subsection">
          <h3>2. 使用Store</h3>
          <p>在组合式API中使用store非常简单，只需调用store函数并使用解构获取需要的属性：</p>
          <div class="code-example">
            <pre><code>import { useStore } from './store'
import { storeToRefs } from 'pinia'

// 在组件中
export default {
  setup() {
    const store = useStore()
    
    // 解构获取响应式状态和getters
    // 注意：必须使用storeToRefs保持响应性
    const { name, doubleCount } = storeToRefs(store)
    
    // actions可以直接解构
    const { increment } = store
    
    return {
      name,
      doubleCount,
      increment
    }
  }
}</code></pre>
          </div>
        </div>
        
        <div class="subsection">
          <h3>3. 多个Store</h3>
          <p>Pinia的一个优势是可以定义和使用多个store，它们可以相互引用：</p>
          <div class="code-example">
            <pre><code>// 在一个store中使用另一个store
import { useUserStore } from './user'

export const useCartStore = defineStore('cart', {
  actions: {
    checkout() {
      const userStore = useUserStore()
      if (userStore.isLoggedIn) {
        // ... 结账逻辑
      }
    }
  }
})</code></pre>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<style scoped>
.tutorial-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

header {
  margin-bottom: 30px;
  border-bottom: 1px solid #eee;
  padding-bottom: 20px;
}

h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1.2rem;
  color: #666;
  margin-bottom: 20px;
}

.tutorial-nav {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 20px;
}

.nav-link {
  padding: 8px 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  text-decoration: none;
  color: #333;
  transition: background-color 0.2s;
}

.nav-link:hover {
  background-color: #e0e0e0;
}

.intro {
  margin-bottom: 40px;
}

.code-example {
  background-color: #f8f8f8;
  border-radius: 6px;
  padding: 15px;
  margin: 15px 0;
  overflow-x: auto;
}

pre {
  margin: 0;
}

code {
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
}

.demo-section {
  margin-bottom: 40px;
}

.card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.btn.primary {
  background-color: #4CAF50;
  color: white;
}

.btn.primary:hover {
  background-color: #3e8e41;
}

.btn.secondary {
  background-color: #f1f1f1;
  color: #333;
}

.btn.secondary:hover {
  background-color: #e0e0e0;
}

.btn.danger {
  background-color: #f44336;
  color: white;
}

.btn.danger:hover {
  background-color: #d32f2f;
}

.btn.small {
  padding: 4px 8px;
  font-size: 0.9rem;
}

.btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.products-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.product-item {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 15px;
}

.product-info {
  margin-bottom: 15px;
}

.product-actions {
  display: flex;
  justify-content: flex-end;
}

.discount-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.discount-form {
  display: flex;
  align-items: center;
  gap: 10px;
}

.discount-form input {
  width: 100px;
}

.cart-items {
  margin-bottom: 20px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.cart-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.total {
  font-size: 1.2rem;
  font-weight: bold;
}

.empty-cart {
  text-align: center;
  padding: 20px;
  color: #666;
}

.explanation {
  margin-top: 40px;
}

.subsection {
  margin-bottom: 30px;
}
</style>
